package main;


import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;

import maquina.gestor.flujo.RemoteGestorTarjeta;
import maquina.interfaz.io.LectorTarjeta;

public class StubLectorTarjeta extends UnicastRemoteObject implements LectorTarjeta {

	
	private static final long serialVersionUID = 6739487575961427532L;
	
	Registry registry;

	public JFrame visual;
	
	protected StubLectorTarjeta(int port) throws RemoteException, AlreadyBoundException {
		super();
		registry = java.rmi.registry.LocateRegistry.createRegistry(port);
		registry.bind("LectorTarjetaMAQUINA", this);
		visual = new JFrame();
		visual.setBounds(300, 300, 200, 200);
		JButton jb = new JButton("Ingresar tarjeta");
		visual.add(jb);
		visual.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jb.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent arg0) {
					RemoteGestorTarjeta gestor;
					try {
						gestor = (RemoteGestorTarjeta) registry.lookup("GestorTarjeta");
						gestor.ingresarTarjeta();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
		});
		visual.setVisible(true);
	}

	public boolean ping() {

		return true;
	}

	public void escribirTarjeta(List<String> candidatos) {
		
		try {
			
		    BufferedWriter out = new BufferedWriter(new FileWriter("tarjeta.txt"));
		    
		    String str = "";
		    
		    for(String candidato: candidatos){
		    
		    	if(!candidato.equals(candidatos.get(0))){
		    	
		    		str += "\n";
		    	}
		    	
		    	str += candidato;
		    }
		    
		    out.write(str);
		    
		    out.close();
		
		} catch (IOException e) {

			System.out.println("Falla el escribir archivo tarjeta");
		}
	}

	public static void main(String[] args) {
		
		if (args.length > 0){
				 
			try{
			    new StubLectorTarjeta(Integer.parseInt(args[0]));
			
			} catch (Exception e) {
				
				System.out.println("No se pudo iniciar StubLectorTarjeta");
			}
		}else
			System.out.println("Parametro faltante."); 
	 }
}
